package com.atguigu.gmall.activity.service.impl;

import com.atguigu.gmall.activity.service.ActivityInfoService;
import com.atguigu.gmall.activity.service.ActivityService;
import com.atguigu.gmall.activity.service.CouponInfoService;
import com.atguigu.gmall.model.activity.ActivityRule;
import com.atguigu.gmall.model.activity.CouponInfo;
import com.atguigu.gmall.model.cart.CarInfoVo;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderDetailVo;
import com.atguigu.gmall.model.order.OrderTradeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mqx
 * @date 2020-12-8 16:54:23
 */
@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityInfoService activityInfoService;

    @Autowired
    private CouponInfoService couponInfoService;

    @Override
    public Map<String, Object> findActivityAndCoupon(Long skuId, Long userId) {
        //一个sku只能有一个促销活动，一个活动有多个活动规则（如满赠，满100送10，满500送50）
        List<ActivityRule> activityRuleList = activityInfoService.findActivityRule(skuId);
        Long activityId = null;
        if(!CollectionUtils.isEmpty(activityRuleList)) {
            //只有一个活动id
            List<Long> activityIdList = activityRuleList.stream().map(ActivityRule::getActivityId).collect(Collectors.toList());
            activityId = activityIdList.get(0);
        }

        //获 取优惠券信息
        List<CouponInfo> couponInfoList = couponInfoService.findCouponInfo(skuId, activityId, userId);

        Map<String, Object> map = new HashMap<>();
        map.put("activityRuleList", activityRuleList);
        map.put("couponInfoList", couponInfoList);
        return map;
    }

    @Override
    public List<CarInfoVo> findCartActivityAndCoupon(List<CartInfo> cartInfoList, Long userId) {
        //获取skuId对应的活动id
        Map<Long, Long> skuIdToActivityIdMap = new HashMap<>();
        //  获取有活动的购物项
        List<CarInfoVo> carInfoVoList = activityInfoService.findCartActivityRuleMap(cartInfoList, skuIdToActivityIdMap);

        //获取skuId对应的优惠券列表
        Map<Long, List<CouponInfo>> skuIdToCouponInfoListMap = couponInfoService.findCartCouponInfo(cartInfoList, skuIdToActivityIdMap, userId);

        //没有参加活动的购物项
        List<CartInfo> noJoinCartInfoList = new ArrayList<>();
        for(CartInfo cartInfo : cartInfoList) {
            Boolean isJoinActivity = false;
            Iterator<Map.Entry<Long, Long>> iterator = skuIdToActivityIdMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, Long> entry = iterator.next();
                Long skuId = entry.getKey();
                if(cartInfo.getSkuId().longValue() == skuId) {
                    isJoinActivity = true;
                    break;
                }
            }
            if(!isJoinActivity) {
                noJoinCartInfoList.add(cartInfo);
            }
        }
        //  把没有活动的购物项生成一组
        if(!CollectionUtils.isEmpty(noJoinCartInfoList)) {
            CarInfoVo carInfoVo = new CarInfoVo();
            carInfoVo.setCartInfoList(noJoinCartInfoList);
            carInfoVo.setActivityRuleList(null);
            carInfoVoList.add(carInfoVo);
        }

        //设置购物项优惠券列表
        for(CarInfoVo carInfoVo1 : carInfoVoList) {
            List<CartInfo> cartInfoList1 = carInfoVo1.getCartInfoList();
            for(CartInfo cartInfo : cartInfoList1) {
                cartInfo.setCouponInfoList(skuIdToCouponInfoListMap.get(cartInfo.getSkuId()));
            }
        }
        return carInfoVoList;
    }

    @Override
    public OrderTradeVo findTradeActivityAndCoupon(List<OrderDetail> orderDetailList, Long userId) {
        /**
         * 促销活动处理，获取购物项最优的对应促销活动规则
         * （如：满减 100减10 200减30 500减70，当前购物项金额250，那么最优为：200减30）
         */
        //记录购物项activityId对应的最优促销活动规则
        Map<Long, ActivityRule> activityIdToActivityRuleMap = activityInfoService.findTradeActivityRuleMap(orderDetailList);

        // skuId 对应的订单明细
        Map<Long, OrderDetail> skuIdToCartInfoMap = new HashMap<>();
        for(OrderDetail orderDetail : orderDetailList) {
            skuIdToCartInfoMap.put(orderDetail.getSkuId(), orderDetail);
        }

        //记录有活动的购物项sku
        List<Long> activitySkuId = new ArrayList<>();
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        //  活动总金额
        BigDecimal activityReduceAmount = new BigDecimal("0");
        //  获取每个活动的最优规则金额，
        if(!CollectionUtils.isEmpty(activityIdToActivityRuleMap)) {
            Iterator<Map.Entry<Long, ActivityRule>> iterator = activityIdToActivityRuleMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, ActivityRule> entry = iterator.next();
                //  活动规则
                ActivityRule activityRule = entry.getValue();
                //  活动规则对应的skuId 列表
                List<Long> skuIdList = activityRule.getSkuIdList();
                List<OrderDetail> detailList = new ArrayList<>();
                for(Long skuId : skuIdList) {
                    detailList.add(skuIdToCartInfoMap.get(skuId));
                }
                activityReduceAmount = activityReduceAmount.add(activityRule.getReduceAmount());

                OrderDetailVo orderDetailVo = new OrderDetailVo();
                orderDetailVo.setActivityRule(activityRule);
                orderDetailVo.setOrderDetailList(detailList);
                orderDetailVoList.add(orderDetailVo);
                //  有活动的skuId列表。
                activitySkuId.addAll(skuIdList);
            }
        }

        //无活动的购物项
        List<OrderDetail> detailList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            if(!activitySkuId.contains(orderDetail.getSkuId())) {
                detailList.add(skuIdToCartInfoMap.get(orderDetail.getSkuId()));
            }
        }
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setActivityRule(null);
        orderDetailVo.setOrderDetailList(detailList);
        orderDetailVoList.add(orderDetailVo);

        //优惠券处理，获取购物项能使用的优惠券
        List<CouponInfo> couponInfoList = couponInfoService.findTradeCouponInfo(orderDetailList, activityIdToActivityRuleMap, userId);

        OrderTradeVo orderTradeVo = new OrderTradeVo();
        //  返现总金额
        orderTradeVo.setActivityReduceAmount(activityReduceAmount);
        //  送货清单
        orderTradeVo.setOrderDetailVoList(orderDetailVoList);
        //  优惠券列表
        orderTradeVo.setCouponInfoList(couponInfoList);
        return orderTradeVo;
    }
}
